package cn.qihua.security;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import cn.qihua.model.SysUser;

public class PasswordHelper {

	private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
	private String algorithmName = "md5";
	private int hashIterations = 2;

	public void setRandomNumberGenerator(
			RandomNumberGenerator randomNumberGenerator) {
		this.randomNumberGenerator = randomNumberGenerator;
	}

	public void setAlgorithmName(String algorithmName) {
		this.algorithmName = algorithmName;
	}

	public void setHashIterations(int hashIterations) {
		this.hashIterations = hashIterations;
	}

	// 密码加密
	public void encryptPassword(SysUser user) {
		user.setSalt(randomNumberGenerator.nextBytes().toHex());
		String newPassword = new SimpleHash(algorithmName, user.getPassword(),
				ByteSource.Util.bytes(user.getCredentialsSalt()),
				hashIterations).toHex();
		//System.out.println("newPassword = " + newPassword);
		user.setPassword(newPassword);
	}

	// 验证密码
	public Boolean validatePassword(SysUser user, String oldPwd) {
		
		String vPassword = new SimpleHash(algorithmName, oldPwd,
				ByteSource.Util.bytes(user.getCredentialsSalt()),
				hashIterations).toHex();
		//System.out.println("vPassword:"+vPassword+" Password:"+user.getPassword());
		return user.getPassword().equals(vPassword);
	}
}
